package com.meibao.cart.service;

import com.meibao.auth.entity.UserInfo;
import com.meibao.cart.interceptor.UserInterceptor;
import com.meibao.cart.pojo.Cart;
import com.meibao.common.enums.ExceptionEnums;
import com.meibao.common.exception.MbException;
import com.meibao.common.utils.JsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class CartService {
    @Autowired
    private StringRedisTemplate redisTemplate;

//    @Autowired
//    private GoodsClient goodsClient;

    static final String KEY_PREFIX = "cart:uid:";

    static final Logger logger = LoggerFactory.getLogger(CartService.class);

    public void addCart(Cart cart) {
        // 获取登录用户
        UserInfo user = UserInterceptor.getUser();
        // Redis的key
        String key = KEY_PREFIX + user.getId();
        //hasKey
        String hasKey = cart.getSkuId().toString();
        // 获取hash操作对象
        BoundHashOperations<String, Object, Object> operation = redisTemplate.boundHashOps(key);
        // 查询是否存在
        Integer num = cart.getNum();
        Boolean boo = operation.hasKey(hasKey);
        if (boo) {
            // 存在，获取购物车数据
            String json = operation.get(hasKey).toString();
            cart = JsonUtils.parse(json, Cart.class);
            // 修改购物车数量
            cart.setNum(num + cart.getNum());
//        } else {
//            // 不存在，新增购物车数据
//            cart.setUserId(user.getId());
//            // 其它商品信息， 需要查询商品服务
//            ResponseEntity<Sku> resp = goodsClient.querySkuById(skuId);
//            if (resp.getStatusCode() != HttpStatus.OK || !resp.hasBody()) {
//                logger.error("添加购物车的商品不存在：skuId:{}", skuId);
//                throw new RuntimeException();
//            }
//            Sku sku = resp.getBody();
//            cart.setImage(StringUtils.isBlank(sku.getImages()) ? "" : StringUtils.split(sku.getImages(), ",")[0]);
//            cart.setPrice(sku.getPrice());
//            cart.setTitle(sku.getTitle());
//            cart.setOwnSpec(sku.getOwnSpec());
        }
        // 将购物车数据写入redis
        operation.put(cart.getSkuId().toString(), JsonUtils.serialize(cart));
    }

    public List<Cart> queryCartList() {
        // 获取登录用户
        UserInfo user = UserInterceptor.getUser();
        // 判断是否存在购物车
        String key = KEY_PREFIX + user.getId();
        if(!redisTemplate.hasKey(key)){
            // 不存在，直接返回
            throw new MbException(ExceptionEnums.CART_NOT_FOUND);
        }
        BoundHashOperations<String, Object, Object> operation = redisTemplate.boundHashOps(key);
        List<Cart> carts = operation.values().stream().map(o -> JsonUtils.parse(o.toString(), Cart.class)).
                collect(Collectors.toList());
        // 查询购物车数据
        return carts;
    }

    public void updateNum(Long skuId, Integer num) {
        //获取登录用户
        UserInfo user = UserInterceptor.getUser();
        //key
        String key = KEY_PREFIX + user.getId();
        String hashKey = skuId.toString();
        // 获取hash操作对象
        BoundHashOperations<String, Object, Object> operation = redisTemplate.boundHashOps(key);
        //判断是否存在
        if(!operation.hasKey(hashKey)){
            // 不存在，直接返回
            throw new MbException(ExceptionEnums.CART_NOT_FOUND);
        }
        //查询购物车
        Cart cart = JsonUtils.parse(operation.get(hashKey).toString(), Cart.class);
        cart.setNum(num);
        //写回redis
        operation.put(hashKey, JsonUtils.serialize(cart));
    }

    public void deleteCart(Long skuId) {
        //获取登录用户
        UserInfo user = UserInterceptor.getUser();
        //key
        String key = KEY_PREFIX + user.getId();
        //删除
        redisTemplate.opsForHash().delete(key, skuId.toString());
    }
}
